package com.llmops.demo;

import com.llmops.core.listener.ChatModelLogListener;
import dev.langchain4j.model.input.structured.StructuredPrompt;
import dev.langchain4j.model.openai.OpenAiChatModel;
import dev.langchain4j.model.output.structured.Description;
import dev.langchain4j.service.AiServices;
import dev.langchain4j.service.UserMessage;
import dev.langchain4j.service.V;

import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class 内容提取 {

    interface JsonExtractor {
        @UserMessage("""
    从文本中提取JSON格式信息,只返回JSON信息,不要输出多余的内容：
    文本：{{input}}
    要求:You must answer strictly in the following JSON format:{{jsonFormat}}
    """)
        String extractPerson(@V("input") String text,@V("jsonFormat") String jsonFormat);
    }

    public static void main(String[] args) {
        OpenAiChatModel chatModel = OpenAiChatModel.builder()
                .baseUrl("https://api.deepseek.com/v1")
                .apiKey("sk-0c3e6a9f9f7a4e63bb855290c544183c")
                .modelName("deepseek-chat")
                .logRequests(true)
                .logResponses(true)
                .listeners(List.of(new ChatModelLogListener()))
                .build();

        JsonExtractor jsonExtractor = AiServices.create(JsonExtractor.class, chatModel);

        // 调用示例
        String person = jsonExtractor.extractPerson("我是张三北京人20岁","{\"name\": (type: string),\"age\": (type: integer)}");
        System.out.println(extractJsonBlock(person)); // 输出：Person[name=王五, age=25, city=北京]

    }
    private static final Pattern JSON_BLOCK_PATTERN = Pattern.compile("(?s)\\{.*\\}|\\[.*\\]");

    private static String extractJsonBlock(String text) {
        Matcher matcher = JSON_BLOCK_PATTERN.matcher(text);
        if (matcher.find()) {
            return matcher.group();
        }
        return text;
    }

}
